<?php

namespace App\Http\Controllers\Member;

use App\Model\FollowUser;
use App\Model\Message;
use App\Model\Search;
use App\Model\Users;
use App\Models\Archive\Archive;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

class indexController extends Controller
{
    //普通用户会员中心


    public function userIndex()
    {

        //dd(session('message'));
        $user = Users::where('id',session('user')->id)->first();
        $now = $user->sign_in;
        $today = date('Y-m-d',time());
        if($now == $today){
            $is_sign = 1;
        }else{
            $is_sign = 0;
        }
        //首页数据
        $documents = Archive::where('user_id',$user->id)->count();
        $fans = FollowUser::where('followed_id',$user->id)->count();
        $follows = DB::table('user_anchor')->where('user_id',$user->id)->count();
        return view('member.userIndex',compact('is_sign','user','documents','fans','follows'));
    }
    //管理员后台
    public function masterIndex()
    {        //首页数据
        $documents = Archive::where('is_del',0)->count();
        $users = Users::count();
        $anchors = DB::table('anchors')->count();
        $videos = Archive::where('is_del',0)->where('archive_type_id',3)->count();
        return view('member.masterIndex',compact('documents','users','anchors','videos'));
    }

    public function sign()
    {
        $data = Input::except('_token');
        if($data['id']!=session('user')->id){
            return '请求错误';
        }else{
            $user = Users::where('id',session('user')->id)->first();
            $arr['points'] = $user->points;
            $points = mt_rand(1,100);
            $arr['points'] += $points;
            $arr['sign_in'] = date('Y-m-d',time());
            if(Users::where('id',$data['id'])->update($arr)){
                return '签到成功，随机获取到' . $points . '积分！';
            }else{
                return '签到失败！';
            }
        }
    }

    public function search()
    {
        $users = Search::groupBy('keyword')->selectRaw('id,keyword,count(*) as sum')->orderBy('sum','desc')->paginate(20);

        $count =  Search::groupBy('keyword')->selectRaw('id,keyword,count(*) as sum')->orderBy('sum','desc')->get();
        $count = count($count);
        return view('member.searchLists',compact('users','count'));
    }

    public function search_del($user_id)
    {
        if(is_numeric($user_id)){
                $result = Search::where('id',$user_id)->delete();
                if($result){
                    return 'success';
                }else{
                    return 'error';
                }

        }else{
            $result = Search::destroy(explode(',',$user_id));
            if($result){
                return 'success';
            }else{
                return 'error';
            }
        }
    }
}
